package com.androidx.paging.datasource

import androidx.paging.PageKeyedDataSource
import com.androidx.paging.model.GoodsModel

/**
 * Created by zhangyuncai on 2020/8/6.
 */
//按页加载，如请求数据时传入page页码
class GoodsPageDataSource:PageKeyedDataSource<Int, GoodsModel>() {
    //初次加载
    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, GoodsModel>
    ) {
        val data = setData(0)
        callback.onResult(data,0,1)
    }
    //加载下一页
    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, GoodsModel>) {
        val data = setData(params.key)
        callback.onResult(data,params.key+1)
    }
    //加载上一页
    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, GoodsModel>) {
        val data = setData(params.key)
        callback.onResult(data,params.key-1)
    }

    //模拟数据
    private fun setData(page: Int): List<GoodsModel> {
        val datas = mutableListOf<GoodsModel>()
        for (index in page * 10 + 1..(page + 1) * 10) {
            datas.add(GoodsModel().apply {
                id = index
                name = "商品名:${index}"
            })
        }
        return datas
    }
}